package com.maple.base.base

import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import com.maple.base.viewModel.BaseVM
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel

abstract class BaseViewActivity<VB : ViewDataBinding, VM : BaseVM>: BaseActivity(), CoroutineScope by MainScope() {

    /**
     * 是否使用多状态视图
     */
    open fun hasUsedStateView(): Boolean = false


    /***
     *  创建 viewModel
     */
    inline fun <reified VM : ViewModel> viewModels(
        noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
    ): Lazy<VM> {
        val factoryPromise = factoryProducer ?: {
            defaultViewModelProviderFactory
        }
        return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
    }


    protected val binding: VB by lazy { DataBindingUtil.setContentView(this, getLayoutId()) as VB }

    abstract fun bindViewModel(): VM

    override fun setContentLayout() {
        super.setContentLayout()
        this.binding.lifecycleOwner = this
        val viewModel = this.bindViewModel()
        this.lifecycle.addObserver(viewModel)
        registerDefUIChange(viewModel)
    }

    private fun registerDefUIChange(viewModel: VM) {
        viewModel.defUI.showDialog.observe(this, Observer {
            showLoading()
        })

        viewModel.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })

        viewModel.defUI.toastEvent.observe(this, Observer {
            showToast(it)
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
        this.binding.unbind()
    }

}